package org.fnzn.web;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.fnzn.bean.LrdUser;
import org.fnzn.bean.vo.UserLoginCheck;
import org.fnzn.service.LoginService;
import org.fnzn.util.CommonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.fnzn.bean.vo.User;
import org.fnzn.core.Result;
import org.fnzn.dao.LrdOrgMapper;
import org.fnzn.exception.MyException;
import org.fnzn.factory.IUser;
import org.fnzn.factory.UserFactory;
import org.fnzn.util.EncryptUtils;
import org.fnzn.util.MD5;
import org.fnzn.util.ResultGenerator;

import lombok.extern.slf4j.Slf4j;


@RestController
@RequestMapping("/Login")
@Slf4j
public class LoginController {
	private static Map<String, UserLoginCheck> logFailMap = new ConcurrentHashMap<String, UserLoginCheck>();
	private static Hashtable<String, HttpSession> htAll = new Hashtable<String, HttpSession>();// 登陆成功后, key:user_id, value:session
	@Autowired
	private LoginService loginService;
	@Autowired
	LrdOrgMapper lrdOrgMapper;
	
	@RequestMapping(value = "/login", produces = "application/json;charset=UTF-8", method = { RequestMethod.POST })	
	public Result login(@RequestBody Map<String,Object> map, HttpServletRequest request) {
        StringBuffer requestURL = request.getRequestURL();
        Map<String, String[]> parameterMap = request.getParameterMap();
        String userId ="";
		String pwdAes="";
		try {
//			userId = EncryptUtils.aesDecrypt(map.get("username").toString());
            userId = map.get("username").toString();
			//pwdAes = EncryptUtils.aesDecrypt(map.get("password").toString());
            pwdAes = map.get("password").toString();
		}catch(Exception e){
			throw new MyException("登陆解密失败");
		}
		// 用户登录验证对象
		UserLoginCheck userLoginCheck = logFailMap.get(userId);
		if (userLoginCheck != null && userLoginCheck.getLoginFailCount() >= 100) {
			long currentTime =System.currentTimeMillis();// 当前系统时间
			long lastWaitTime = logFailMap.get(userId).getLastFailDatetime().getTime();// 最后失败登陆时间
			long waitTime = (lastWaitTime - currentTime) / 1000; // 时间差(计算出相差的秒数)
			if (currentTime < lastWaitTime) {				
				return ResultGenerator.genSuccessResult("登录异常, 账号已被锁定, 请在" + (waitTime/60) + "分钟后再试.");			
			} else {
				logFailMap.get(userId).setLoginFailCount(0);
			}
		} 	
		String pwd = MD5.getMD5(pwdAes);
		LrdUser lrdUser=loginService.findUserByName(userId);
		if (null != lrdUser) {
			if (lrdUser.getUserId().equals(userId)) {
				String resPwd = lrdUser.getPassword();
				// 验证密码
				if (pwd.equals(resPwd)) {// 密码正确						
					IUser iuser=UserFactory.me();
					User user=iuser.user(lrdUser);
					//用户登录成功, 删除失败缓存中的数据。
					logFailMap.remove(userId);						
					HttpSession oldSession = htAll.get(userId);						
					if (oldSession != null) {
						try {
							oldSession.invalidate();
						} catch (Exception e) {
						}
					}					
					htAll.remove(user.getUser_id());
					HttpSession session = request.getSession(true);
					session.setAttribute("user", user);
					htAll.put(userId, session);
					Map<String,Object> resultmap=new HashMap<String,Object>();
					resultmap.put("x-access-token", session.getId());
					resultmap.put("user", user);
					return ResultGenerator.genSuccessResult(resultmap);
				} else {// 密码错误

					// 得到long类型的 "最后登录失败时间" + "30 分钟"
					long timeDifference = System.currentTimeMillis() + (30 * 60 * 1000);

					if (userLoginCheck == null) {
						userLoginCheck = new UserLoginCheck();

						//是新的用户, 登录失败次数设置为1
						userLoginCheck.setLoginFailCount(1);
					} else {
						// 获取到登录失败次数
						int failCount = userLoginCheck.getLoginFailCount();
						// 在原来的失败次数上 +1
						userLoginCheck.setLoginFailCount(failCount + 1);
					}							
					//设置用户登录失败的最后时间
					userLoginCheck.setLastFailDatetime(new Date(timeDifference));
					//添加到 登录失败的缓存中
					logFailMap.put(userId, userLoginCheck);
					return ResultGenerator.genSuccessResult("用户名或密码错误,你还有"+(5-logFailMap.get(userId).getLoginFailCount())+"次机会");
				}
			} else {
				return ResultGenerator.genSuccessResult("用户名或密码错误,你还有"+(5-logFailMap.get(userId).getLoginFailCount())+"次机会");
			}
		} else {
			return ResultGenerator.genSuccessResult("用户名或密码错误");
		}	
	}
	@RequestMapping(value = "/logout", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET })
	public Result logout(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		User user = this.getSessionUser(request);
		if (null != user) {
			user.getHt().remove(user.getUser_id());
			htAll.remove(user.getUser_id());
			user = null;
			HttpSession session = request.getSession();
			session.invalidate();
		} else {
			HttpSession session = request.getSession();
			session.invalidate();
		}
		return ResultGenerator.genSuccessResult();
		
	}
	public User getSessionUser(HttpServletRequest request){
		return (User)request.getSession().getAttribute("user");
	}

    @RequestMapping(value = "/getUserInfo", produces = "application/json;charset=UTF-8", method = { RequestMethod.GET })
    public Result getUserInfo(HttpServletRequest request) {

        User user = CommonUtil.getUser();
        LrdUser lrdUser=loginService.findUserByName(user.getUser_id());
        IUser iuser=UserFactory.me();
        User userinfo=iuser.user(lrdUser);

        HttpSession session = request.getSession(true);
        session.setAttribute("user", userinfo);
        Map<String,Object> resultmap=new HashMap<String,Object>();
        resultmap.put("x-access-token", session.getId());
        resultmap.put("user", userinfo);
        return ResultGenerator.genSuccessResult(resultmap);
    }
}
